class CustomersController < ApplicationController
  before_action :set_customer, only: [:show, :edit, :update, :destroy]
  before_action :set_page_title

  respond_to :html

  def index
    @customers = Customer.where(build_search(search_params)).order(created_at: :desc).page(params[:page])
    
    respond_to do |format|
      format.html {}      
      format.json {render json:@customers }
    end
    
  end

  def show
    redirect_to edit_customer_path(@customer)
  end

  def new
    @customer = Customer.new
    respond_with(@customer)
  end

  def edit
  end

  def create
    @customer = Customer.new(customer_params)

    respond_to do |format|
      if @customer.save
        format.html { redirect_to edit_customer_path(@customer), success: '创建成功！' }
        format.json { render :show, status: :created, location: @customer }
      else
        format.html { render :new }
        format.json { render json: @customer.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @customer.update(customer_params)
        format.html { redirect_to edit_customer_url(@customer), success: '更新成功！' }
        format.json { render :show, status: :ok, location: @order }
      else
        format.html { render :edit }
        format.json { render json: @customer.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @customer.destroy
    respond_with(@customer)
  end

  private
    def set_customer
      @customer = Customer.find(params[:id])
    end

    def customer_params
      params.require(:customer).permit(:name, :address, :tel, :fax, :tax_no, :bank, :bank_account, :bank_address)
    end
    
    def search_params     
        if params[:customer].present?  
          customer_params.permit(:name)
        end                     
    end

    def set_page_title
      @page_title = "客户"
    end
end
